# -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import fields
from openerp.osv import osv


class apply_delivery_exchange(osv.osv):
    _name = 'apply.delivery.exchange'
    _columns = {
        'suite_old': fields.selection([(1, u'选项1'), (2, u'选项2'), (3, u'选项3'), (4, u'选项4'), (5, u'选项5'), (6, u'选项6'),
                                       (7, u'选项7'), (8, u'选项8'), (9, u'选项9'), (10, u'选项10')], string='套装'),
        'suite_new': fields.selection([(1, u'选项1'), (2, u'选项2'), (3, u'选项3'), (4, u'选项4'), (5, u'选项5'), (6, u'选项6'),
                                       (7, u'选项7'), (8, u'选项8'), (9, u'选项9'), (10, u'选项10')], string='套装'),
        'suit_product_old_list': fields.one2many('suit.product.list', 'exchange_wizard_old_id', string=u'退回产品'),
        'suit_product_new_list': fields.one2many('suit.product.list', 'exchange_wizard_new_id', string=u'目标产品'),
        'apply_delivery_id': fields.many2one('apply.delivery', string=u'提货记录'),
    }
    
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        delivery_row = self.pool.get('apply.delivery').browse(cr, uid, context.get('active_id'), context=context)
        if not delivery_row.is_shipping:
            raise osv.except_osv(u'错误', u"本条提货记录没有发货完成，请取消本条提货记录，再进行换货(或者重新提货)!")
        for change_row in delivery_row.change_apply_delivery_ids:
            if not change_row.is_shipping and not change_row.is_canceled:
                raise osv.except_osv(u'错误', u"存在换货单没有发货完成，请取消原提货记录，再进行换货!")
        return_val = super(apply_delivery_exchange, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type,
                                                             context=context, toolbar=toolbar, submenu=submenu)
        return return_val

    def create(self, cr, uid, vals, context=None):
        """
        相当于一个换货申请,只有填充了  suit_product_new_list 和 suit_product_old_list才算完整
        :return:
        """
        if not vals.get("suit_product_new_list", False) or not vals.get('suit_product_old_list', False):
            raise osv.except_osv(u'错误', u"必须填写要退回产品和要换取的的产品!")
        return super(apply_delivery_exchange, self).create(cr, uid, vals, context=context)

    def onchange_suite_new(self, cr, uid, ids, suite_new, apply_delivery_id, context=None):
        """
        选择想要调整的套装 如果券订单上存在 该套装, 则返回所选套装的产品 如果不存在该套装 则报错(管理员不受约束)
        :param suite_new:
        :param apply_delivery_id:
        :return:
        """
        if suite_new and apply_delivery_id:
            apply_delivery = self.pool.get('apply.delivery').browse(cr, uid, apply_delivery_id, context=context)
            card_product_obj = self.pool.get('sale.order.card.product')
            card_product_ids = card_product_obj.search(cr, uid, [('order_id', '=', apply_delivery.card_so_id.id),
                                                                      ('suite', '=', suite_new)], context=context)
            product_lines = []
            if not card_product_ids and uid != SUPERUSER_ID:
                raise osv.except_osv(u'错误', u"卡券订单中没有这个选项!")
            for card_product_row in card_product_obj.browse(cr, uid, card_product_ids, context=context):
                product_lines.append([0, 0, {'product_id': card_product_row.product_id.id,
                                             'product_num': card_product_row.product_qty,
                                             'card_product_num': card_product_row.product_qty,
                                             'card_product_id': card_product_row.id}])
            return {'value': {'suit_product_new_list': product_lines}}

    def get_apply_delievery(self, cr, uid, context=None):
        """
        获取要换货的提货申请记录的id
        :return:
        """
        apply_delivery = self.pool.get('apply.delivery').browse(cr, uid, context.get('active_id'), context=context)
        return apply_delivery.suite

    def get_apply_delievery_product(self, cr, uid, context=None):
        """
        获取旧的提货申请上的产品 列表
        :return:
        """
        apply_delivery = self.pool.get('apply.delivery').browse(cr, uid, context.get('active_id'), context=context)
        line_vals_list = []
        for line in apply_delivery.card_so_id.sale_order_card_product_ids:
            if line.suite == apply_delivery.suite:
                line_vals_list.append((0, 0, {'product_id': line.product_id.id, 'product_num': line.product_qty,
                                              'card_product_num': line.product_qty,
                                              'card_product_id': line.id}))
        return line_vals_list

    _defaults = {
        'suite_old': get_apply_delievery,
        'suit_product_old_list': get_apply_delievery_product,
        'apply_delivery_id': lambda self, cr, uid, ctx: ctx.get('active_id'),
    }

    def exchange_apply_delivery(self, cr, uid, ids,context=None):
        """
        复制原提货申请,修改所选套装 填充原提货申请
        :return: 返回到新提货申请的页面
        """
        apply_delivery_obj = self.pool.get('apply.delivery')
        apply_delivery_wizard = self.browse(cr, uid, ids, context=context)
        copy_data = apply_delivery_obj.copy_data(cr, uid, apply_delivery_wizard.apply_delivery_id.id,
                                                 default=None, context=context)
        tmp = copy_data.copy()
        if not apply_delivery_wizard.apply_delivery_id:
            raise osv.except_osv(u'警告', u'操作有误！请重新操作，如果还是提示报错，请联系管理员！')
        tmp.update({'suite': apply_delivery_wizard.suite_new,
                    'is_multiple_choice_one':apply_delivery_wizard.apply_delivery_id.is_multiple_choice_one,
                    'code': apply_delivery_wizard.apply_delivery_id.code.id,
                    'copy_code': apply_delivery_wizard.apply_delivery_id.copy_code,
                    'password': apply_delivery_wizard.apply_delivery_id.password,
                    'orign_apply_delivery_id': apply_delivery_wizard.apply_delivery_id.orign_apply_delivery_id and
                                               apply_delivery_wizard.apply_delivery_id.orign_apply_delivery_id.id or
                                               apply_delivery_wizard.apply_delivery_id.id})  # 一张提货订单可能存在多次换货
        # 对换货生成的提货记录,进行换货 新的换货订单统统只记录最原始的 提货记录
        context.update({"apply_delivery_exchange_id":ids[0]})
        apply_delivery_id = apply_delivery_obj.create(cr, uid, tmp, context=context)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'apply.delivery',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': apply_delivery_id
        }

class suit_product_list(osv.osv):

    _name = 'suit.product.list'
    _columns = {
         'product_id': fields.many2one('product.product',string=u'产品', required=True),
         'product_num': fields.integer(string=u'数量', required=True),
         'exchange_wizard_old_id': fields.many2one('apply.delivery.exchange'),
         'exchange_wizard_new_id': fields.many2one('apply.delivery.exchange'),
         'card_product_num': fields.integer(string=u"选项对应的产品数量", help=u'卡券订单对应的选项'),
         'card_product_id': fields.many2one('sale.order.card.product',string=u"选项对应的产品数量", help=u'卡券订单对应的选项')
    }
    _defaults = {
        'product_num': 1,
        'card_product_num': 1,
    }

    def onchange_product_num(self, cr, uid, ids, product_num, card_product_num, card_product_id, context=None):
        """
        判断套装的数量 和 要退货产品的数量大小.
        退回或者换区的产品的数量不能大于 原套装上的产品数量...
        :param product_num:
        :param card_product_num:
        :param card_product_id:
        """
        if product_num <= 0:
            return {'warning': {'title': u"警告！", 'message': u"换取的产品数量不能小于1"}}
        if product_num > card_product_num and card_product_id and uid != SUPERUSER_ID:
            return {'warning': {'title': u"警告！", 'message': u"换货产品数量不能大于选项产品规定数量"},
                    'value': {'product_num': card_product_num}}

    def onchange_product_id(self, cr, uid, ids, product_id, context=None):
        """
        对产品 和套裝进行核对 看产品是否在 套装内.(管理员不受限制)
        :param product_id:
        :return:
        """
        return_val = {}
        if product_id:
            apply_delivery = self.pool.get('apply.delivery').browse(cr, uid, context.get('apply_delivery_id'), context=context)
            card_product_obj = self.pool.get('sale.order.card.product')
            card_product_id = card_product_obj.search(cr, uid, [('order_id', '=', apply_delivery.card_so_id.id),
                                                                 ('suite', '=', context.get('suite')),
                                                                 ('product_id', '=', product_id)], context=context)
            if not card_product_id and uid != SUPERUSER_ID:
                return_val.update({'warning': {'title': u"警告！", 'message': u"您选的产品不在原卡券订单上，请核对后在选择"},
                                   'value': {'product_id': False}})
            else:
                card_product_row = card_product_obj.browse(cr, uid, card_product_id, context=context)
                return_val.update({'value': {'card_product_num': card_product_row.product_qty or 1,
                                             'product_num': card_product_row.product_qty or 1,
                                             'card_product_id': card_product_id}})
        return return_val